package com.nightsoul.servlet3.test.chapter2.web;


import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

/**
 * ServletContextListener动态添加要放在ServletContainerInitializer中, 见{@link MyServletContainerInitializer}
 * @author zj
 *
 */
@WebListener
public class DynamicInitListener implements ServletContextListener {
    @Override
    public void contextInitialized(final ServletContextEvent sce) {
        ServletContext sc = sce.getServletContext();

        //sc.addListener("com.nightsoul.servlet3.test.chapter2.web.DynamicServletContextListener");
        //sc.addListener(DynamicServletContextListener.class);
        sc.addListener(DynamicHttpSessionListener.class);

        Dynamic filterDynamic = sc.addFilter("dynamicFilter", DynamicFilter.class);
        filterDynamic.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/*");
        filterDynamic.setAsyncSupported(true);
        

        ServletRegistration.Dynamic dynamic1 = sc.addServlet("dynamicServlet1", DynamicServlet.class);
        dynamic1.setLoadOnStartup(1);
        dynamic1.addMapping("/dynamic1");

        ServletRegistration.Dynamic dynamic2 = sc.addServlet("dynamicServlet2", "com.nightsoul.servlet3.test.chapter2.web.DynamicServlet");
        dynamic2.addMapping("/dynamic2");

        ServletRegistration.Dynamic dynamic3 = sc.addServlet("dynamicServlet3", new DynamicServlet());
        dynamic3.addMapping("/dynamic3");

    }

    @Override
    public void contextDestroyed(final ServletContextEvent sce) {
    }

}
